const jwt = require('jsonwebtoken');
const { query } = require('../config/database');

// JWT认证中间件
const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
        return res.status(401).json({
            success: false,
            message: '访问令牌缺失'
        });
    }

    jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key', (err, user) => {
        if (err) {
            return res.status(403).json({
                success: false,
                message: '无效的访问令牌'
            });
        }
        req.user = user;
        next();
    });
};

// 用户验证中间件
const validateUser = async (req, res, next) => {
    try {
        const { openid } = req.user;

        const sql = 'SELECT id, openid, status FROM users WHERE openid = ?';
        const results = await query(sql, [openid]);

        if (results.length === 0 || results[0].status !== 1) {
            return res.status(404).json({
                success: false,
                message: '用户不存在或已被禁用'
            });
        }

        req.user.id = results[0].id;
        next();
    } catch (error) {
        console.error('用户验证失败:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
};

// 速率限制中间件
const rateLimit = require('express-rate-limit');

const apiLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15分钟
    max: 100, // 限制每个IP每15分钟最多100个请求
    message: {
        success: false,
        message: '请求过于频繁，请稍后再试'
    },
    standardHeaders: true,
    legacyHeaders: false,
});

module.exports = {
    authenticateToken,
    validateUser,
    apiLimiter
};